/*
 * DBAccessController.java
 *
 * Created on January 9, 2007, 3:53 PM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */
package database;

import javax.naming.*;
import javax.sql.*;
import java.sql.*;

/**
 *
 * @author Brandon Lim
 */
public class DBAccessController {

    Connection connection = null;

    public DBAccessController(String jndiName) {
        getConnection(jndiName);
    }

    private void getConnection(String jndi) {

        try {
            Context ctx = new InitialContext();
            if (ctx == null) {
                throw new Exception("Boom - No Context");
            }

            DataSource ds = (DataSource) ctx.lookup("java:comp/env/" + jndi);

            // DataSource ds =  (DataSource) ctx.lookup(jndi);

            if (ds != null) {
                connection = ds.getConnection();
            }
        } catch (Exception e) {
            e.printStackTrace();
            connection = null;
        }
    }

    public int customRollBack() {

        try {
            if (connection == null) {
                return -1;
            }
            connection.rollback();
        } catch (SQLException e) {
            e.printStackTrace();
            return -1;
        }
        return 1;
    }

    public ResultSet execSelectQuery(String sql) {

        try {
            if (connection == null) {
                return null;
            }
            Statement s = connection.createStatement();
            return s.executeQuery(sql);
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }

    public int execUpdateQuery(String sql) {

        try {
            if (connection == null) {
                return -1;
            }
            Statement s = connection.createStatement();
            return s.executeUpdate(sql);
        } catch (SQLException e) {
            e.printStackTrace();
            return -1;
        }
    }

    public void terminate() {

        try {
            connection.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
